package com.kadoufall.recommender.web;

import com.kadoufall.recommender.dao.NewsRepository;
import com.kadoufall.recommender.dao.UserOperationRepository;
import com.kadoufall.recommender.dao.UserRepository;
import com.kadoufall.recommender.model.News;
import com.kadoufall.recommender.model.User;
import com.kadoufall.recommender.model.UserOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/user_operation")
public class UserOperationController {
    @Autowired
    UserOperationRepository userOperationRepository;

    @Autowired
    NewsRepository newsRepository;

    @RequestMapping(value = "/add/{userId}/{newsId}", method = RequestMethod.GET)
    public UserOperation add(@PathVariable Long userId, @PathVariable Long newsId) {
        UserOperation userOperation = new UserOperation();
        userOperation.setUserId(userId);
        userOperation.setNewsId(newsId);
        userOperation.setPreference(1);
        userOperation.setReadTime(new Timestamp(new Date().getTime()));
        // 先应该查询这个用户有没有此次访问记录
        List<UserOperation> userOperationList =  userOperationRepository.findByUserId(userOperation.getUserId());
        boolean flag = true;
        for (UserOperation uo : userOperationList) {
            if (uo.getNewsId() == userOperation.getNewsId()) {
                // 已经记录过了，则不再记录，标志位设为否
                flag = false;
                break;
            }
        }
        if (flag) {
            News news = newsRepository.findById(newsId.longValue());
            int newViewNum = news.getViewNum();
            newViewNum++;
            news.setViewNum(newViewNum);
            newsRepository.save(news);

            return userOperationRepository.save(userOperation);
        }
        else {
            return null;
        }

    }

    @RequestMapping(value = "/del/{userId}/{newsId}", method = RequestMethod.GET)
    public void del(@PathVariable Long userId, @PathVariable Long newsId) {
        userOperationRepository.deleteByUserIdAndNewsId(userId, newsId);

        News news = newsRepository.findById(newsId.longValue());
        int newViewNum = news.getViewNum();
        newViewNum--;
        news.setViewNum(newViewNum);
        newsRepository.save(news);
    }

    @RequestMapping(value = "/find_by_user_and_news/{userId}/{newsId}", method = RequestMethod.GET)
    public List<UserOperation> findByUserIdAndNewsId(@PathVariable Long userId, @PathVariable Long newsId) {
        return userOperationRepository.findByUserIdAndNewsId(userId, newsId);
    }
}
